/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.service.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.StringUtils;
import yhao.infra.service.datasource.mybatis.mapper.scanner.AutoMapperScanner;

import static org.springframework.util.Assert.notNull;

/**
 * automapper组件 bean的扫描类
 *
 * @see AutoMapperScanner
 * @author yoara
 */
public class MapperScannerConfig implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware {
    private String basePackage;
    private ApplicationContext applicationContext;
    private String baseDaoBeanName;

    public void setBasePackage(String basePackage) {
        this.basePackage = basePackage;
    }

    public void setBaseDaoBeanName(String baseDaoBeanName) {
        this.baseDaoBeanName = baseDaoBeanName;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        notNull(this.basePackage, "Property 'basePackage' is required");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // left intentionally blank
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        AutoMapperScanner scanner = new AutoMapperScanner(registry);
        scanner.setResourceLoader(this.applicationContext);
        scanner.setBaseDaoBeanName(this.baseDaoBeanName);
        scanner.registerFilters();
        scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
    }
}
